package git.bankview.wl.report;

import java.util.*;
import java.text.*;
import java.io.*;

import laya.semi.process.*;
import git.bankview.sl.report.ReportCommon;
import git.bankview.sl.report.ReportParameter;

import git.bankview.sl.db.*;

import org.apache.log4j.Logger;

import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRParameter;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.engine.util.JRLoader;

public class JasperPromptedParametersGetter
	implements IGenericClassActivity
{
	private static Logger log = Logger.getLogger(JasperPromptedParametersGetter.class);

	public void execute(IProcessContext oCtx)
		throws Exception
	{
		String[] params = oCtx.getActivityParameter().split(":");
		String jasperFileName = params[0];
		String jasperParamsName = params[1];
		
		String jasperUploadFileName = (5 == params.length ? params[2] : null);
		String transidName = (5 == params.length ? params[3] : null);
		String translabelName = (5 == params.length ? params[4] : null);
		
		File jasperFile = (File)oCtx.getField(jasperFileName);
		Vector jasperParams = new Vector();

		try
		{
			JasperReport oReport = (JasperReport)JRLoader.loadObject(jasperFile);
			JRParameter[] vParam = oReport.getParameters();
			
			Vector standardParams = new Vector();
			for (int i = 0; i < vParam.length; ++i)
			{
				if (!vParam[i].isSystemDefined() && vParam[i].isForPrompting()) // for user defined ones
					jasperParams.addElement(new ReportParameter(vParam[i]));
				else if (ReportCommon.JR_IS_IGNORE_PAGINATION.equals(vParam[i].getName())) // find standard ones for append to tail
					standardParams.addElement(new ReportParameter(vParam[i]));
			}
			jasperParams.addAll(standardParams);
			
			if (null != jasperUploadFileName)
			{
				String transid = findTransidFromFilename((String)oCtx.getField(jasperUploadFileName));
				oCtx.setField(transidName, transid);
				oCtx.setField(translabelName, oReport.getName());
			}
			
			oCtx.setField(jasperParamsName, jasperParams);
		}
		catch(JRException e)
		{
			log.warn("", e);
			throw new ActivityException(oCtx, "jasperUpload.err.unknowFormat");
		}	
	}
	
	private String findTransidFromFilename(String fileName)
	{
		int nStep = 1;
		StringBuffer oTransid = new StringBuffer();
		for (int i = 0; 0 < nStep && i < fileName.length(); ++i)
		{
			char ch = fileName.charAt(i);
			switch(nStep)
			{
				case 1:
					if ('0' <= ch && '9' >= ch)
					{
						oTransid.append(ch);
						nStep = 2;
					}
					break;
				case 2:
					if ('0' > ch || '9' < ch)
						nStep = 0;
					else
						oTransid.append(ch);
					break;
			}
		}
		
		return oTransid.toString();
	}
}
